﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WyUnity.Data.DataAccess;
using WyUnity.Utility.ExtentionMethods;
using WyUnity.Data.DataAccess.Dialect;
using WyUnity.Utility;

namespace WyUnity.Data
{
    public static class DbManager
    {
        private static ISqlDialect _defaultDialect;
        private static string _defaultConnectionString;
        /// <summary>
        /// 打开一个数据连接
        /// </summary>
        /// <param name="dialect">数据库方言类别(默认为SQLServer)</param>
        /// <param name="connectionString">数据库连接字符串(默认为当前系统数据库)</param>
        /// <returns>数据库连接会话</returns>
        public static DbSession OpenSession(ISqlDialect dialect = null, string connectionString = null)
        {
            if (connectionString.IsNullOrEmpty() && _defaultDialect != null)
            {
                dialect = _defaultDialect;
                connectionString = _defaultConnectionString;
            }

            //如果仍然找不到连接字符串，则使用config文件中的连接字符串
            if (connectionString.IsNullOrEmpty())
                connectionString = Util.GetConfigConnectionString("db");

            //如果最后仍然得不到连接字符串，抛出异常
            if (connectionString.IsNullOrEmpty())
                throw new DAException("找不到默认的连接字符串");

            return new DbSession(
                dialect.NullCheck(SqlDialectMng.GetMSSqlDialect()),
                connectionString);
        }

        public static void SetDefaultConnectionString(ISqlDialect dialect, string connectionString)
        {
            _defaultConnectionString = connectionString;
            _defaultDialect = dialect;
        }

        ///// <summary>
        ///// 获取当前的数据库会话
        ///// </summary>
        //public static DbSession GetCurrentSession()
        //{
        //    //TODO:保存当前连接会话

        //    return OpenSession();
        //}
    }
}
